import React, { Component } from 'react';
import { message } from 'antd'
import './login.css'
import { withFormik, Form, Field, ErrorMessage  } from 'formik'
import * as Yup from 'yup'
import   { post }  from '../../utils/post'

// 验证规则：
const REG_UNAME = /^[a-zA-Z\d]{6}$/
const REG_PWD = /^[a-zA-Z\d]{5,12}$/


export default class Login extends Component {
    state = {
        username: '',
        email: '',
        password1: '',
        password2: ''
    }
    addRight = () => {
        const container = document.getElementById('container')
        container.classList.add('penal-right-active')
    }

    removeRight = () => {
        const container = document.getElementById('container');
        container.classList.remove('penal-right-active');
    }

    goIndex = () => {
        this.props.history.push('/index')
        //发一个post请求之后的then
        //同时也要把token放到localstorage里边
        if (!localStorage.getItem('usersMessage')) {
            console.log('设置了usersMessage');
            let usersMessage = {
                username: 12345678,
                nickname: '少年阿滨',
                sex: true,
                avater: "https://img1.baidu.com/it/u=2716398045,2043787292&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
                createdAt: "2022-01-27T14:06:04.288Z",
                updatedAt: "2022-01-27T14:07:38.669Z"
            }
            localStorage.setItem('usersMessage', JSON.stringify(usersMessage))
        }
        if (!localStorage.getItem(import.meta.env.VITE_APP_TOKEN)) {
            let token = '123456' + import.meta.env.VITE_APP_TOKEN
            localStorage.setItem(import.meta.env.VITE_APP_TOKEN,token)
        }
    }

    usernameChange = (event) =>{
        const username = event.target.value
        this.setState({username})
    }

    passwordChange = (event) =>{
        const password1 = event.target.value
        this.setState({password1})
    }

    rightChange = (event) =>{
        const password2 = event.target.value
        this.setState({password2})
    }

    handleSubmit = async (event) =>{
        event.preventDefault()
        const { username,email,password1,password2 } = this.state
        if(!REG_UNAME.test(username)){
            message.info('用户名长度需为6位，只能出现数字、字母' )
            return
        }
        if(!REG_PWD.test(password1)){
            message.info('密码长度为5到12位，只能出现数字、字母')
            return
        }
        if(password1 !== password2){
            (()=>{
                message.info('两次密码输入不一致!')
            })()
            return
        }
        const password = password1
        const res = await post('/api/register',{
            username,
            email,
            password
        })
        const { status } =  res.data.meta
        if(status == 201){
            (()=>{
                message.info('注册成功!')
            })()
            //初始化个人信息
            const container = document.getElementById('container');
            container.classList.remove('penal-right-active');
            this.setState({
                username: '',
                password1:'',
                password2: ''
            })
        }else{
            (()=>{
                message.info('用户名已存在!')
            })()
        }
        console.log(status);
        
    }
    render() {
        return (
            <div className='Wrapper'>
                <div className="container" id="container">

                    {/* <!-- 注册页面 --> */}
                    <div className="form-container sign-up-container">
                        <form onSubmit={this.handleSubmit}>
                            <h1 className='h1'>注 册</h1>
                            {/* <!-- 公共组件 --> */}
                            <div className="social-container">
                                <a href="#"><i className="fab fa-qq"></i></a>
                                <a href="#"><i className="fab fa-weixin"></i></a>
                                <a href="#"><i className="fab fa-weibo"></i></a>
                            </div>
                            <input name="username"  placeholder="用户名..." value={this.state.username} onChange={this.usernameChange} />
                            <input name="password1" type="password"  placeholder="密码..." value={this.state.password1} onChange={this.passwordChange} />
                            <input name="password2" type="password"   placeholder="确认密码..." value={this.state.password2} onChange={this.rightChange} />
                            
                            <button type='submit'>注 册</button>
                        </form>
                    </div>

                    {/* <!-- 登录页面 --> */}
                    <div className="form-container sign-in-container">
                        <Form>
                            <h1 className='h1'>登 入</h1>
                            {/* <!-- 公共组件 --> */}
                            <div className="social-container">
                                <a href="#"><i className="fab fa-qq"></i></a>
                                <a href="#"><i className="fab fa-weixin"></i></a>
                                <a href="#"><i className="fab fa-weibo"></i></a>
                            </div>
                            <Field name="username"   placeholder="请输入账号..." />
                            <ErrorMessage
                                className="error"
                                name="username"
                                component="div"
                            />
                            <Field type="password" name="password" id="password" placeholder="请输入密码..." />
                            <ErrorMessage
                                className="error"
                                name="password"
                                component="div"
                            />
                            <a href="#" className="forget">忘记密码</a>
                            <button type="submit">登 入</button>
                        </Form>
                    </div>

                    {/* <!-- 覆盖容器 --> */}
                    <div className="overlay-container">
                        <div className="overlay">

                            {/* <!-- 覆盖左边 --> */}
                            <div className="overlay-penal overlay-left-container">
                                <h1 className='h1'> 欢迎 回来👏</h1>
                                <p className='p'>
                                    朋友，这里永远是你生活中的第二个港湾😊😊
                                </p>
                                <button className="ghost" id="signIn" onClick={this.removeRight}>登 入</button>
                            </div>

                            {/* <!-- 覆盖右边 --> */}
                            <div className="overlay-penal overlay-right-container">
                                <h1 className='h1'>你好 朋友👋</h1>
                                <p className='p'>
                                    输入您的个人详细信息，与我们一起开始旅程
                                </p>
                                <button className="ghost" id="signUp" onClick={this.addRight}>注 册</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}


// 使用 withFormik 高阶组件包装 Login 组件，为 Login 组件提供属性和方法
Login = withFormik({
    // 提供状态：
    mapPropsToValues: () => ({ username: '', password: ''}),
  
    // 添加表单校验规则
    validationSchema: Yup.object().shape({
      username: Yup.string()
        .required('账号为必填项')
        .matches(REG_UNAME, '长度为6位，只能出现数字、字母'),
      password: Yup.string()
        .required('密码为必填项')
        .matches(REG_PWD, '长度为5到12位，只能出现数字、字母'),        
    }),
  
    // 表单的提交事件
    handleSubmit: async (values, { props }) => {
      // 获取账号和密码
      const { username, password } = values
      console.log('拿到的数据',values);
      // console.log('表单提交了', username, password)
      // 发送请求
      const res = await post('/api/login', {
        username,
        password
      })
      console.log('返回的数据',res);
      const { token } = res.data.data
      const { status } = res.data.meta
      if (status === 200) {
        // 登录成功
        (()=>{
            message.info('登陆成功!')
        })()
        localStorage.setItem(import.meta.env.VITE_APP_TOKEN,token)
        // console.log('登录后返回的数据',res.data.data.userInfo);
        const data = res.data.data.userInfo
        // console.log(JSON.parse(data.sex),'这是性别');
        let usersMessage = {
            _id: data._id,
            username: data.username,
            nickname: data.nickname ? data.nickname : `用户${username}`,
            sex: JSON.parse(data.sex) ? '男' : '女' ,
            avater: data.avater ? data.avater : 'https://img0.baidu.com/it/u=1329709505,2760911286&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800',
            profile: data.profile ? data.profile : '该用户很懒,没有做自我介绍',
            email:data.email ? data.email : '该用户没有留下邮箱地址' ,
            date: data.date ? data.date : '未知',
            age: data.age ? data.age : 18,
            createdAt: data.createdAt,
            updatedAt: data.updatedAt
        }
        localStorage.setItem('usersMessage',JSON.stringify(usersMessage));
        props.history.push('/index')
       
        // 注意：无法在该方法中，通过 this 来获取到路由信息
        // 所以，需要通过 第二个对象参数中获取到 props 来使用 props
      } else{
        // 登录失败
        (()=>{
            message.info('账号或者密码错误!')
        })()
        // Toast.info(description, 2, null, false)
      }
    }
  })(Login)
  